package org.gd.rjdbc.context;

import org.gd.rjdbc.annotation.TableField;

import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Date;

public class RJDBCParser {

    static void parseSqlElement(ResultSet resultSetLine, Field field, Object newInstance, TableField ann)
            throws SQLException, IllegalAccessException {
        try {
            if(field.getType().equals(Date.class)) {
                field.set(newInstance, new Date(resultSetLine.getDate(ann.name()).getTime()));
            } else if(field.getType().equals(String.class) || ann.clazz().equals(String.class)) {
                field.set(newInstance, resultSetLine.getString(ann.name()));
            } else if(field.getType().equals(Integer.class) || ann.clazz().equals(Integer.class)) {
                if(!field.getType().equals(Integer.class)) {
                    field.setInt(newInstance, resultSetLine.getInt(ann.name()));
                } else {
                    field.set(newInstance, resultSetLine.getInt(ann.name()));
                }
            } else if(field.getType().equals(Double.class) || ann.clazz().equals(Double.class)) {
                if(!field.getType().equals(Double.class)) {
                    field.setDouble(newInstance, resultSetLine.getDouble(ann.name()));
                } else {
                    field.set(newInstance, resultSetLine.getDouble(ann.name()));
                }
            } else if(field.getType().equals(Float.class) || ann.clazz().equals(Float.class)) {
                if(!field.getType().equals(Float.class)) {
                    field.setFloat(newInstance, resultSetLine.getFloat(ann.name()));
                } else {
                    field.set(newInstance, resultSetLine.getFloat(ann.name()));
                }
            } else if(field.getType().equals(BigDecimal.class) || ann.clazz().equals(BigDecimal.class)) {
                field.set(newInstance, resultSetLine.getBigDecimal(ann.name()));
            } else if(field.getType().equals(Boolean.class) || ann.clazz().equals(Boolean.class)) {
                if(!field.getType().equals(Long.class)) {
                    field.setBoolean(newInstance, resultSetLine.getBoolean(ann.name()));
                } else {
                    field.set(newInstance, resultSetLine.getBoolean(ann.name()));
                }
            } else if(field.getType().equals(Long.class) || ann.clazz().equals(Long.class)) {
                if(!field.getType().equals(Long.class)) {
                    field.setLong(newInstance, resultSetLine.getLong(ann.name()));
                } else {
                    field.set(newInstance, resultSetLine.getLong(ann.name()));
                }
            }
        } catch (SQLException e) {
            e.printStackTrace(System.err);
        }
    }
}
